package com.hjy.config;

import com.alibaba.fastjson.JSONObject;
import com.hjy.common.domain.request.GoodsReq;
import com.hjy.common.domain.response.GoodsRes;
import com.hjy.common.result.Goods;
import com.hjy.mapper.GoodsMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class MqConsumer {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue(name = "subtract_num"))
    public void subtractNum(Goods goods, Channel channel, Message message) {
        message.getMessageProperties().setMessageId(UUID.randomUUID().toString());

        goodsMapper.count(goods.getNum(),goods.getId());
        // 因为有缓存，所以要删除缓存 在添加
        String redisKey = "goodsList:list:";
        stringRedisTemplate.delete(redisKey);
        GoodsReq req = new GoodsReq();
        List<GoodsRes> list = goodsMapper.goodsList(req);
        stringRedisTemplate.opsForValue().set(redisKey, JSONObject.toJSONString(list));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }


}
